package com.example.t470p.facechecktickets.View;

import android.app.Activity;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.t470p.facechecktickets.Bean.CheckQRCodeResponse;
import com.example.t470p.facechecktickets.Bean.CheckResultBean;
import com.example.t470p.facechecktickets.Bean.CheckTicketMessageResult;
import com.example.t470p.facechecktickets.Bean.IDFreeBean;
import com.example.t470p.facechecktickets.Bean.ImformationSuccessBean;
import com.example.t470p.facechecktickets.Customer.LoadingDialog;
import com.example.t470p.facechecktickets.Customer.MarqueeTextView;
import com.example.t470p.facechecktickets.DynamicFaceMatch.utils.ToastUtils;
import com.example.t470p.facechecktickets.R;
import com.example.t470p.facechecktickets.Sax.CheckTicketMessageHandler;
import com.example.t470p.facechecktickets.Utils.CustomString;
import com.example.t470p.facechecktickets.Utils.DesUtils;
import com.example.t470p.facechecktickets.Utils.LogUtil;
import com.example.t470p.facechecktickets.Utils.MyBitmapUtils;
import com.example.t470p.facechecktickets.Utils.SPUtil;
import com.example.t470p.facechecktickets.Utils.ThreadManager;
import com.example.t470p.facechecktickets.Utils.ToastUtil;
import com.example.t470p.facechecktickets.Utils.util;
import com.example.t470p.facechecktickets.httpUtils;
import com.google.gson.Gson;
import com.synjones.handsetS8.BarReaderModule;
import com.synjones.handsetS8.BarScanResult;
import com.synjones.handsetS8.IDCardReaderModule;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.m1card.M1CardReader;
import com.synjones.multireaderlib.MultiReader;

import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

public class CheckSHActivity extends Activity implements View.OnClickListener {

    private MarqueeTextView ticket;
    private TextView number;
    private TextView numberType;
    private TextView timeBegin;
    private TextView time;
    private TextView checkState;
    private TextView backState;
    private TextView name;
    private TextView id;
    private Button btQR;
    private Button btID;
    private ImageView headShow;
    private TextView tvMode;
    private RelativeLayout bg;
    private boolean isRequset;

    private EditText teTest;
    private String barcode = "";
    private String string;

    //左右箭头 显示
    private ImageView leftClick;
    private ImageView rightClick;

    //计入按钮点击状态
    private boolean isIDClickAble = true;
    private boolean isQRClickAble = true;


    private static final String TAG = "zyf_MainActivity";

    private ReadCardThread ReadCardThreadhandler;
    private boolean reading = false;
    private String status = "";
    private List<ImformationSuccessBean.SaleinfoTicketListBean> saleinfoTicketList;

    /************************扫码************************/
    BarReaderModule barReaderModule;             //扫描头
    public boolean bNeedCheckTicket = true;    //检票标志位
    private String m_StrBarCode;                //二维码号码
    public String m_UpdateImgPath;            //需要上传的图片路径
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    /************************M1卡************************/
    boolean findingCard = false;
    private byte data[] = new byte[1024];//接收buf
    private int dataLen = 0;//接收数据长度
    IDCardReaderModule idCardReaderModule;
    public M1CardReader m1Reader;
    MultiReader multiReader;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    String m_strIDCard; //ID 卡号


    private static final int ReadID = 0;
    private static final int ReadQR = 1;

    public String BaseUrl;
    public String GeteNo;
    public String mLocationName;
    public String mLocationPassword;
    private LoadingDialog loadingDialog;
    private static int Page;
    private String mAddress;
    private String mName;
    private IDFreeBean idFreeBean;
    private CheckResultBean checkResultBean;

    Handler mHanler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ReadID:
//                    CloseReader();
                    IDCard idcard = (IDCard) msg.obj;
                    if (idcard != null) {
                        clearText("1");
                        m_strIDCard = idcard.getIDCardNo();
                        mAddress = idcard.getAddress();
                        mName = idcard.getName();
                        ticket.setText(m_strIDCard);
                        // 去网络请求  身份证
                        BaseUrl = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFBASEURL, CustomString.BASEURL);
                        GeteNo = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFGATENUMBER, "");
                        mLocationName = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFUSERNAME, "admin");
                        mLocationPassword = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFPASSWORDD, "demo@123");
                        //获取到身份证 那么就去请求   扫描获取到的身份证号， 是 解密后的
//                        idFreeRequset(m_strIDCard);
//                        BaseUrl = "http://192.168.20.33:8888/base";
//                        GeteNo = "A010202";
                        CheckIDCode(m_strIDCard, GeteNo);
                    }
                    break;

                case ReadQR:
                    if (!isRequset) {
                        clearText("2");
                        Bundle bundle = msg.getData();
                        m_StrBarCode = bundle.getString("PROCESSOR_QRCODE_DATE");
                        try {
                            // 使用解密来判断是否 可以 解密  如果可以 那么就不是票号， 那么久要 当证件号传过去 ，
                            String decrypt = DesUtils.decrypt(m_StrBarCode);
                            ticket.setText(m_StrBarCode);
                            // 去网络请求  二维码
                            BaseUrl = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFBASEURL, CustomString.BASEURL);
                            GeteNo = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFGATENUMBER, "");
                            mLocationName = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFUSERNAME, "admin");
                            mLocationPassword = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFPASSWORDD, "demo@123");
                            //如果可以解密，那么就是 自己的码过来的， 传递解密后的过去
//                        BaseUrl = "http://192.168.20.33:8888/base";
//                        GeteNo = "A010202";
                            isRequset = true;
                            CheckIDCode(decrypt, GeteNo);
                            // IDSendDate(m_StrBarCode);
//                        QRSendDate("*110001JN607/");
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 如果解密不了 那么就是 票号 按照原样传过去
                            try {
                                // QRSendDate(m_StrBarCode);
                                // 去网络请求  二维码
                                BaseUrl = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFBASEURL, CustomString.BASEURL);
                                GeteNo = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFGATENUMBER, CustomString.BASEURL);
                                mLocationName = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFUSERNAME, "admin");
                                mLocationPassword = (String) SPUtil.get(CheckSHActivity.this, CustomString.ZYFPASSWORDD, "demo@123");
                                //如果可以解密，那么就是 自己的码过来的， 传递解密后的过去
//                            BaseUrl = "http://192.168.20.33:8888/base";
//                            GeteNo = "A010202";
                                ticket.setText(m_StrBarCode);
                                isRequset = true;
                                CheckQRCode(m_StrBarCode, GeteNo);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        teTest.setText("");
                                    }
                                });
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else {
                        ToastUtil.showToast("正在网络请求，请稍后访问");
                    }
                    break;
            }

        }
    };

    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {

                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    private void QRRequest() {
        // 先封装一个 JSON 对象
        final JSONObject param = new JSONObject();
        try {
            param.put("searchDataType", "1");
            param.put("searchData", m_StrBarCode);
            param.put("checkCount", 1);
            param.put("gateNo", GeteNo);
            param.put("isCollectionGate", "N");
            param.put("rowKey", "");
            param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
            param.put("timestamp", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final String url = BaseUrl + CustomString.QR_CHECK_URL;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String ss = httpUtils.postJson(url, param);
                // 获取到数据 去解析数据并进行显示
                try {
                    idFreeBean = new Gson().fromJson(ss, IDFreeBean.class);
                    //获取到数据  去给页面显示
                    if (idFreeBean.getCode().equals("0")) {
                        showSucFace();
                    } else {
                        showErrFace();
                    }
                } catch (Exception e) {
                    showErrFace();
                    ToastUtil.showToast("网络访问失败，请检查网络");
                }
            }
        };
        ThreadManager.getThreadPool().execute(runnable);

    }


    private void idFreeRequset(String IDCard) {
        // 先封装一个 JSON 对象
        final JSONObject param = new JSONObject();
        try {
            param.put("searchDataType", "2");
            param.put("searchData", IDCard);
            param.put("checkCount", "1");
            param.put("gateNo", GeteNo);
            param.put("address", "");
            param.put("humanName", "");
            param.put("isCollectionGate", "N");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final String url = BaseUrl + CustomString.FREE_MESSAGE_URL;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String ss = httpUtils.postJson(url, param);
                // 获取到数据 去解析数据并进行显示
                try {
                    idFreeBean = new Gson().fromJson(ss, IDFreeBean.class);
                    //获取到数据  去给页面显示
                    if (idFreeBean.getCode().equals("0")) {
                        showSucFace();
                    } else {
                        showErrFace();
                    }
                } catch (Exception e) {
                    showErrFace();
                    isRequset = false;
                    ToastUtil.showToast("网络访问失败，请检查网络");

                }
            }
        };
        ThreadManager.getThreadPool().execute(runnable);

    }

    // 二维码检票
    void CheckQRCode(final String m_StrBarCode, final String m_strGateNo) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Log.i(TAG, Thread.currentThread().getName());
                try {

                    String sendUrl = BaseUrl + "/checkTicketInterface/checkTicket.do";

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
                    String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
//                    System.out.println(timestamp);
                    Map<String, String> map = new HashMap<String, String>();

                    map.put("ticketNo", m_StrBarCode);
                    map.put("userName", mLocationName);
                    map.put("password", mLocationPassword);
                    map.put("gateNo", m_strGateNo);
                    map.put("timestamp", timestamp);


                    String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");

//                    System.out.println(sign);
                    String sendDate = "ticketNo=" + m_StrBarCode
                            + "&userName=" + mLocationName
                            + "&password=" + mLocationPassword
                            + "&gateNo=" + m_strGateNo
                            + "&timestamp=" + timestamp
                            + "&sign=" + sign;

                    final String ss = httpUtils.sendPost(sendUrl, sendDate);
                    // TODO: 2019/7/30 response,检票

//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            ToastUtil.showToast(ss);
//                        }
//                    });
                    final CheckTicketMessageResult checkTicketMessageResult = parseXMLWithSAX(ss);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setXMLText(m_StrBarCode, checkTicketMessageResult);
                            isRequset = false;
                        }
                    });

                    if (!checkTicketMessageResult.getCheckTicketMessageResult().getCode().equals("0")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                isRequset = false;
                                ToastUtil.showToast(checkTicketMessageResult.getCheckTicketMessageResult().getMessage());
                            }
                        });
                    }
//                    CheckQRCodeResponse response = new Gson().fromJson(ss, CheckQRCodeResponse.class);
//                    Log.i(TAG, response.toString());
//                    //code 为0 此票有效，code为其他
//                    if (response.getCode().equals("0")) {
////                        setText(response);
//
//                    } else {
////                        setText(response);
//                    }

                } catch (Exception e) {
//                    PlayAudioFile("服务器连接失败");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            isRequset = false;
                            ToastUtil.showToast("checkTicket异常：服务器连接失败");
                        }
                    });
                }
                Looper.loop();
            }
        }).start();
    }

    //身份证 验证
    void CheckIDCode(final String m_StrBarCode, final String m_strGateNo) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();

                Log.i(TAG, Thread.currentThread().getName());
                try {

//                    String sendUrl = "http://" + BaseUrl + "/checkTicketInterface/checkTicket.do";
                    String sendUrl = BaseUrl + "/checkTicketInterface/checkTicket.do";

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
                    String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
                    Map<String, String> map = new HashMap<String, String>();


                    map.put("certificateNo", m_StrBarCode);
                    map.put("userName", mLocationName);
                    map.put("password", mLocationPassword);
                    map.put("gateNo", m_strGateNo);
                    map.put("timestamp", timestamp);

                    String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");

//                    System.out.println(sign);
                    String sendDate = "certificateNo=" + m_StrBarCode
                            + "&userName=" + mLocationName
                            + "&password=" + mLocationPassword
                            + "&gateNo=" + m_strGateNo
                            + "&timestamp=" + timestamp
                            + "&sign=" + sign;

                    String ss = httpUtils.sendPost(sendUrl, sendDate);
                    // TODO: 2019/7/30 response,检票
                    //解析 ss  由于是 xml 所以就直接拿了

                    final CheckTicketMessageResult checkTicketMessageResult = parseXMLWithSAX(ss);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            isRequset = false;
                            setXMLText(m_StrBarCode, checkTicketMessageResult);

                        }
                    });
                    if (!checkTicketMessageResult.getCheckTicketMessageResult().getCode().equals("0")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                isRequset = false;
                                ToastUtil.showToast(checkTicketMessageResult.getCheckTicketMessageResult().getMessage());
                            }
                        });
                    }


//                    CheckTicketMessageResult response = new Gson().fromJson(ss, CheckTicketMessageResult.class);
//                    Log.i(TAG, response.toString());
//                    //code 为0 此票有效，code为其他
//                    if (response.getCheckTicketMessageResult().getCode().equals("0")) {
////                        setText(response);
//
//                    } else {
////                        setText(response);
//                    }

                } catch (Exception e) {
//                    PlayAudioFile("服务器连接失败");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("checkTicket异常：服务器连接失败");
                            PlayAudioFile("服务器连接失败");
                        }
                    });
                }
                Looper.loop();
            }
        }).start();
    }

    private void setXMLText(String m_StrBarCode, CheckTicketMessageResult ss) {
        try {
            ticket.setText(ss.getCheckTicketMessageResult().getTicketName());
            number.setText("可通行 " + ss.getCheckTicketMessageResult().getTotalMaxNumber() + " 人");
            numberType.setText(ss.getCheckTicketMessageResult().getMessage() + " " + ss.getCheckTicketMessageResult().getMsg());
            id.setText(m_StrBarCode);
            PlayAudioFile(ss.getCheckTicketMessageResult().getMessage());
        } catch (Exception e) {
//            ToastUtil.showToast("checkTicket异常：服务器连接失败");
//            PlayAudioFile("服务器连接失败");
        }

    }


    /**
     * 生成签名结果
     *
     * @param sArray 要签名的数组
     * @param key    通知密钥
     * @return 签名结果字符串
     */
    public static String buildMysign(Map<String, String> sArray, String key) {
        try {
            Map<String, String> result = paraFilter(sArray);
            String prestr = createLinkString(result); //把数组所有元素，按照“参数参数值”的模式拼接成字符串
            prestr = key + prestr; //把接口密钥+拼接后的字符串直接连接起来
            String mysign = md5(prestr);
            if (mysign != null) {
                mysign = mysign.toUpperCase();
                System.out.println(mysign);
            }
            return mysign;
        } catch (Exception e) {

        }
        return null;
    }

    /*
     * md5编码
     */
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数参数值”的模式拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            prestr = prestr + key + value;
        }
        return prestr;
    }

    private void showErrFace() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                clearText("0");
                ticket.setText("验票失败，无法通行");
                bg.setBackgroundResource(R.mipmap.redbg);
                headShow.setImageResource(R.mipmap.error);
            }
        });
    }


    private void showSucFace() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //idFreeBean
                ticket.setText(idFreeBean.getData().getTicketName());
                number.setText(idFreeBean.getData().getPassPersonSum() + "人");
                numberType.setText(idFreeBean.getData().getBarcodeNo());
                timeBegin.setText(idFreeBean.getData().getTicketValidStartTime());
                time.setText(idFreeBean.getData().getTicketValidEndTime());
//        checkState.setText(idFreeBean.getData().getCertificateNo());
//        backState.setText(idFreeBean.getData().getCertificateName());
                name.setText(idFreeBean.getData().getCertificateName());
                id.setText(idFreeBean.getData().getCertificateNo());

                if (idFreeBean.getData().getBase64Pic() != null && !idFreeBean.getData().getBase64Pic().equals("")) {
                    headShow.setImageBitmap(MyBitmapUtils.base64ToBitmap(idFreeBean.getData().getBase64Pic()));
                    LogUtil.v("有图片");
                } else {
                    headShow.setImageResource(R.mipmap.bgicon);
                    LogUtil.v("没有图片");
                }

                bg.setBackgroundResource(R.mipmap.greenbg);
                headShow.setImageResource(R.mipmap.success);
            }
        });


    }


    /**
     * @param type 0 是不需要，1是身份证，2是二维码
     */
    private void clearText(String type) {
        if (type.equals("1")) {
            headShow.setImageResource(R.mipmap.idicrd);
        } else if (type.equals("2")) {
            headShow.setImageResource(R.mipmap.qrnew);
        }
        bg.setBackgroundResource(R.mipmap.bg);
        ticket.setText("");
        number.setText("");
        numberType.setText("");
        time.setText("");
        timeBegin.setText("");
        checkState.setText("");
        backState.setText("");
        name.setText("");
        id.setText("");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //取消标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_science);

        // 获取配置文件信息
        String ConfigPath = getSDPath() + "/config.ini";
        GetConfig(ConfigPath);
        initView();

        //获取TTS引擎
        mSpeech = new TextToSpeech(CheckSHActivity.this, new CheckSHActivity.TTSListener());
        clearText("1");
        loadingDialog = new LoadingDialog(this);


    }


    private void initView() {

        ticket = (MarqueeTextView) findViewById(R.id.tv_ticket1);
        number = (TextView) findViewById(R.id.tv_number1);
        numberType = (TextView) findViewById(R.id.tv_number_type1);
        timeBegin = (TextView) findViewById(R.id.tv_time_begin1);
        time = (TextView) findViewById(R.id.tv_time_end1);
        checkState = (TextView) findViewById(R.id.tv_state);
        backState = (TextView) findViewById(R.id.tv_back);
        name = (TextView) findViewById(R.id.tv_name1);
        id = (TextView) findViewById(R.id.tv_id1);
        tvMode = (TextView) findViewById(R.id.tv_mode);
        headShow = (ImageView) findViewById(R.id.iv_title_head);
        leftClick = (ImageView) findViewById(R.id.iv_left);
        rightClick = (ImageView) findViewById(R.id.iv_right);
        bg = (RelativeLayout) findViewById(R.id.rl_bg);

        btQR = (Button) findViewById(R.id.bt_bread);
        btID = (Button) findViewById(R.id.bt_id);

        teTest = (EditText) findViewById(R.id.et_test);

        //M1卡初始化
//        idCardReaderModule = IDCardReaderModule.getInstance(this);
//        multiReader = idCardReaderModule.getBaseMultiReader();
//        isConnect = idCardReaderModule.isOpen();
//        if (!isConnect) {
//            idCardReaderModule.open();
//        }
//        isConnect = idCardReaderModule.isOpen();
//        if (null == m1Reader) {
//            m1Reader = new M1CardReader(multiReader);
//        }


        //扫描头初始化
//        m_StrBarCode = "";
//        barReaderModule = BarReaderModule.getInstance(this);
//        barReaderModule.open();

//        btID.setOnClickListener(this);
//        btQR.setOnClickListener(this);
        leftClick.setOnClickListener(this);
        rightClick.setOnClickListener(this);
        clearText("2");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_id:
                Page = 0;
                clearText("1");
                leftClick.setVisibility(View.INVISIBLE);
                rightClick.setVisibility(View.INVISIBLE);
                loadingDialog.show();
                tvMode.setText("身份证检票");
                btID.setClickable(false);
                checkID();
                break;
            case R.id.bt_bread:
                Page = 0;
                clearText("2");
                leftClick.setVisibility(View.INVISIBLE);
                rightClick.setVisibility(View.INVISIBLE);
                btQR.setEnabled(false);
                tvMode.setText("二维码检票");
                loadingDialog.show();
                redScan();
                break;
        }

    }

    private void checkID() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();
    }

    private void redScan() {
        barReaderModule.scan(new BarReaderModule.OnScanResult() {
            @Override
            public void onScanResult(BarScanResult barScanResult) {
                if (barScanResult.code != 0) {
                    btQR.setEnabled(true);
                    loadingDialog.dismiss();
                    ToastUtil.showToast("未检测到二维码");
                    PlayAudioFile("未检测到二维码");
                    return;
                } else {
                    int end_pos = barScanResult.barMsg.lastIndexOf("\r\n");
                    if (0 > end_pos) {
                        m_StrBarCode = barScanResult.barMsg;
                    } else {
                        m_StrBarCode = barScanResult.barMsg.substring(0, end_pos);
                    }
                    if (m_StrBarCode != null && !m_StrBarCode.equals("") && !m_StrBarCode.equals("0")) {

                        m_StrBarCode = m_StrBarCode.replaceAll("\r|\n", "");
                        btQR.setEnabled(true);
                        loadingDialog.dismiss();
                        //扫描二维码成功，去发送网络请求  ReadQR
                        mHanler.sendEmptyMessage(ReadQR);
//                        Log.d(TAG, "onScanResult: 扫码成功" + m_StrBarCode);
                    } else {
                        bNeedCheckTicket = true;
                        ToastUtil.showToast("二维码数据解析失败");
                        loadingDialog.dismiss();

                    }
                }
            }
        });

    }

    //读卡线程
    class ReadCardThread extends Thread {
        public void run() {
            OpenReader();
            long t = System.currentTimeMillis();
            while (reading) {//读卡器上电需要时间，通过获取samvid判断读卡器是否已工作
                String samvID = idCardReaderModule.getSamvIDString();
                if (samvID != null && samvID.length() > 0)
                    break;
                util.sleep(50);//如果超时，则重新打开读卡器
                if (System.currentTimeMillis() - t > 2000) {
                    t = System.currentTimeMillis();
                    idCardReaderModule.close();
                    idCardReaderModule.open();
                }
            }
            try {
                IDCardReaderRetInfo retInfo;
                retInfo = idCardReaderModule.getIDcardInfo();
                if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btID.setClickable(true);
                        }
                    });
                    status = "";
                    Thread.sleep(500);
                    mHanler.obtainMessage(ReadID, retInfo.card).sendToTarget();
                    loadingDialog.dismiss();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btID.setClickable(true);
                        }
                    });
                    status = util.bytesToHexString(new byte[]{retInfo.sw1, retInfo.sw2, retInfo.sw3});
                    Thread.sleep(200);
                    mHanler.obtainMessage(ReadID, null).sendToTarget();
                    loadingDialog.dismiss();
                    ToastUtil.showToast("身份证读取失败");
                    PlayAudioFile("身份证读取失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public void StopRead() {
            reading = false;
            interrupted();
            try {
                join(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            ReadCardThreadhandler = null;
        }
        idCardReaderModule.close();
    }

    /*
     * 获取配置信息
     */
    public boolean GetConfig(String ConfigPath) {
        boolean ret = false;
        try {
            FileInputStream fis = null; // 读
            Properties pp;

            pp = new Properties();
            fis = new FileInputStream(ConfigPath);
            pp.load(fis);

            BaseUrl = pp.get("SericeUrl").toString();
            GeteNo = pp.get("GateNO").toString();
            mLocationName = pp.get("user_name").toString();
            mLocationPassword = pp.get("password").toString();
            if (BaseUrl != null) {
                SPUtil.put(CheckSHActivity.this, CustomString.ZYFBASEURL, BaseUrl);
                LogUtil.v(BaseUrl);
            }
            if (GeteNo != null) {
                SPUtil.put(CheckSHActivity.this, CustomString.ZYFGATENUMBER, GeteNo);
                LogUtil.v(GeteNo);
            }
            if (mLocationName != null) {
                SPUtil.put(CheckSHActivity.this, CustomString.ZYFUSERNAME, mLocationName);
                LogUtil.v(mLocationName);
            }
            if (mLocationPassword != null) {
                SPUtil.put(CheckSHActivity.this, CustomString.ZYFPASSWORDD, mLocationPassword);
                LogUtil.v(mLocationPassword);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /*
     * 获取SD卡路径
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    private CheckTicketMessageResult parseXMLWithSAX(String result) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader reader = factory.newSAXParser().getXMLReader();
            CheckTicketMessageHandler handler = new CheckTicketMessageHandler();
            reader.setContentHandler(handler);
            reader.parse(new InputSource(new StringReader(result)));
            return handler.getMessage();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CheckTicketMessageResult();
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        } else {
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_ADD, null);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            char pressedKey = (char) event.getUnicodeChar();
            barcode += pressedKey;
        }
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            if (barcode != null && !barcode.equals("")) {
                // 那么就去请求服务器
//                SelfToastUtil.getInstance(AnhuiActivity.this).show(etScan.getText().toString());
                Message message = Message.obtain();
                message.what = ReadQR;
                Bundle bundle = new Bundle();
                string = teTest.getText().toString();
                bundle.putString("PROCESSOR_QRCODE_DATE", string.trim());
                message.setData(bundle);
                mHanler.sendMessage(message);
                barcode = "";
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        teTest.setText("");
                    }
                });
            }
        }
        return super.dispatchKeyEvent(event);
    }
}
